import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:screen/screen.dart';
import 'package:flutter_tencentplayer/flutter_tencentplayer.dart';
import 'package:easydubbing/tencentPlayer/widget/tencent_player_bottom_widget.dart';
import 'package:easydubbing/tencentPlayer/widget/tencent_player_gesture_cover.dart';
import 'package:easydubbing/tencentPlayer/widget/tencent_player_loading.dart';

import '../main.dart';


class FullVideoPage extends StatefulWidget {
  final double aspectRatio;
  final PlayType playType;
  final int rotation;
  final String dataSource;
  final bool isInView;
  final String id;
  final TencentPlayerController controller;

  //UI
  final bool showBottomWidget;
  final bool showClearBtn;


  FullVideoPage({this.controller, this.showBottomWidget = true, this.showClearBtn = true, this.dataSource, this.playType = PlayType.network, this.aspectRatio, this.rotation, this.isInView, this.id});

  @override
  _FullVideoPageState createState() => _FullVideoPageState();
}

class _FullVideoPageState extends State<FullVideoPage> {
  TencentPlayerController controller;
  VoidCallback listener;
  bool isInView;
  bool isGetComment = false;
  List commList;
  List<Widget> comment = [];


  bool isLock = false;
  bool showCover = false;
  Timer timer;


  _FullVideoPageState() {
    listener = () {
      if (!mounted) {
        return;
      }
     setState(() {});
    };
  }

  @override
  void initState() {
    super.initState();
    this.isInView = widget.isInView;
    controller = widget.controller;
    SystemChrome.setEnabledSystemUIOverlays([]);
    if(widget.aspectRatio>1)
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.landscapeLeft,
      DeviceOrientation.landscapeRight,
    ]);
    controller.addListener(listener);
    hideCover();
//    ForbidShotUtil.initForbid(context);
    Screen.keepOn(true);
  }

  @override
  void didUpdateWidget(FullVideoPage oldWidget) {
    if(widget.isInView != oldWidget.isInView){
      setState(() {
        this.isInView = widget.isInView;
      });
      if(!widget.isInView) {
        controller.pause();
      }
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  dispose() {
    SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.top, SystemUiOverlay.bottom]);
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
    controller.removeListener(listener);
    if (widget.controller == null) {
      controller.dispose();
    }
//    ForbidShotUtil.disposeForbid();
    Screen.keepOn(false);
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async{
        Navigator.pop(context, controller);
        return true;
      },
      child:  Scaffold(
        body: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () {
            hideCover();
          },
          onLongPress: (){
            setState(() {
              controller.setRate(2.0);
            });
          },
          onLongPressEnd: (e){
            setState(() {
              controller.setRate(1.0);
            });
          },
          onDoubleTap: () {
            if (!widget.showBottomWidget || isLock) return;
            if (controller.value.isPlaying) {
              setState(() {
                controller.pause();
              });
            } else {
              setState(() {
                controller.play();
              });
            }
          },
          child:Container(
            color: Colors.black,
            child: Stack(
              overflow: Overflow.visible,
              alignment: Alignment.center,
              children: <Widget>[
                /// 视频
                RotatedBox(
                  quarterTurns: widget.rotation~/90,
                  child: AspectRatio(
                    aspectRatio: controller.value.aspectRatio,
                    child: TencentPlayer(controller,),
                  ),
                ),
                /// 支撑全屏
                Container(),
                /// 半透明浮层
                showCover ?Container(
                  alignment: Alignment.bottomCenter,
                  child: Container(
                    height: 50,
                    decoration: BoxDecoration(
                      boxShadow: [
                        BoxShadow(
                          offset: Offset(0.0,10.0),
                            color:Color(0x7f000000),
                            blurRadius: 20
                        )
                      ]
                    ),
                  ),
                ) : SizedBox(),
                /// 处理滑动手势
                Offstage(
                  offstage: isLock,
                  child: TencentPlayerGestureCover(
                    controller: controller,
                    showBottomWidget: widget.showBottomWidget,
                    behavingCallBack: delayHideCover,
                  ),
                ),
                !controller.value.isPlaying?Container(
                  alignment: Alignment.center,
                  child: ClipOval(
                    child: InkWell(
                      onTap: (){
                        setState(() {
                          controller.play();
                        });
                      },
                      child: Container(
                        height: 60,
                        width: 60,
                        color: Color(0x7f000000),
                        padding: EdgeInsets.only(left: 3),
                        child: Container(
                          decoration: BoxDecoration(
                              image: DecorationImage(
                                  image: ExactAssetImage('assets/images/player_play.png'),
                                  fit: BoxFit.scaleDown
                              )
                          ),
                        ),
                      ),
                    ),
                  ),
                ): SizedBox(),
                /// 加载loading
                TencentPlayerLoading(controller: controller, iconW: 53,),
                /// 头部浮层
                !isLock && showCover ? Positioned(
                  top: 0,
                  left: MediaQuery.of(context).padding.top,
                  child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      Navigator.pop(context, controller);
                    },
                    child: Container(
                      padding: EdgeInsets.only(top: 34, left: 10),
                      child: Image.asset('assets/images/icon_back.png', width: 20, height: 20, fit: BoxFit.contain, color: Colors.white,
                      ),
                    ),
                  ),
                ) : SizedBox(),
                /// 锁
                showCover ? Align(
                  alignment: Alignment.centerLeft,
                  child: GestureDetector(
                    behavior: HitTestBehavior.opaque,
                    onTap: () {
                      setState(() {
                        isLock = !isLock;
                      });
                      delayHideCover();
                      if (Platform.isAndroid) {
                        DeviceOrientation deviceOrientation = controller.value.orientation < 180 ? DeviceOrientation.landscapeRight : DeviceOrientation.landscapeLeft;
                        if (isLock) {
                          SystemChrome.setPreferredOrientations([
                            deviceOrientation
                          ]);
                        } else {
                          SystemChrome.setPreferredOrientations([
                            DeviceOrientation.landscapeLeft,
                            DeviceOrientation.landscapeRight,
                          ]);
                        }
                      }
                    },
                    child: Container(
                      color: Colors.transparent,
                      padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top, right: 20, bottom: 20, left: MediaQuery.of(context).padding.top,),
                      child: Image.asset(isLock ? 'assets/images/player_lock.png' : 'assets/images/player_unlock.png', width: 38, height: 38,),
                    ),
                  ),
                ): SizedBox(),
                /// 进度、清晰度、速度
                Offstage(
                  offstage: !widget.showBottomWidget,
                  child: Padding(
                    padding: EdgeInsets.only(left: MediaQuery.of(context).padding.top, right: MediaQuery.of(context).padding.bottom),
                    child: TencentPlayerBottomWidget(
                      isShow: !isLock && showCover,
                      controller: controller,
                      showClearBtn: widget.showClearBtn,
                      behavingCallBack: () {
                        delayHideCover();
                      },
                    ),
                  ),
                ),
                comment.length==0?SizedBox():
                Container(
                  alignment: Alignment.topCenter,
                  child: Stack(
                    children: comment,
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }



  hideCover() {
    if (!mounted) return;
    setState(() {
      showCover = !showCover;
    });
    delayHideCover();
  }

  delayHideCover() {
    if (timer != null) {
      timer.cancel();
      timer = null;
    }
    if (showCover) {
      timer = new Timer(Duration(seconds: 6), () {
        if (!mounted) return;
        setState(() {
          showCover = false;
        });
      });
    }
  }
}
